<template>
  <div class="system-stats">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>系统统计</h1>
      <p class="page-description">查看系统运行状态和整体数据统计</p>
    </div>
    
    <!-- 系统状态卡片 -->
    <div class="status-section">
      <h2>系统状态</h2>
      <div class="status-grid">
        <div class="status-card">
          <div class="status-icon">
            <el-icon :size="32" :color="systemStore.isConnected ? '#67C23A' : '#F56C6C'">
              <Connection v-if="systemStore.isConnected" />
              <Close v-else />
            </el-icon>
          </div>
          <div class="status-content">
            <div class="status-title">WebSocket连接</div>
            <div class="status-value" :class="systemStore.isConnected ? 'text-success' : 'text-danger'">
              {{ systemStore.isConnected ? '已连接' : '未连接' }}
            </div>
            <div class="status-description">
              {{ systemStore.isConnected ? '数据实时同步中' : '连接已断开，请检查网络' }}
            </div>
          </div>
        </div>
        
        <div class="status-card">
          <div class="status-icon">
            <el-icon :size="32" color="#409EFF">
              <DataBoard />
            </el-icon>
          </div>
          <div class="status-content">
            <div class="status-title">监控币种</div>
            <div class="status-value text-primary">
              {{ formatNumber(systemStore.totalCoins, 0) }}
            </div>
            <div class="status-description">
              正在监控的加密货币种类
            </div>
          </div>
        </div>
        
        <div class="status-card">
          <div class="status-icon">
            <el-icon :size="32" color="#E6A23C">
              <Document />
            </el-icon>
          </div>
          <div class="status-content">
            <div class="status-title">数据记录</div>
            <div class="status-value text-warning">
              {{ formatNumber(systemStore.totalRecords, 0) }}
            </div>
            <div class="status-description">
              累计处理的爆仓记录数
            </div>
          </div>
        </div>
        
        <div class="status-card">
          <div class="status-icon">
            <el-icon :size="32" color="#909399">
              <Timer />
            </el-icon>
          </div>
          <div class="status-content">
            <div class="status-title">运行时间</div>
            <div class="status-value text-info">
              {{ formatUptime(uptime) }}
            </div>
            <div class="status-description">
              系统持续运行时长
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 数据统计 -->
    <div class="stats-section">
      <h2>数据统计</h2>
      <div class="stats-grid">
        <!-- 总体统计 -->
        <div class="stat-card large">
          <div class="stat-header">
            <h3>总体爆仓统计</h3>
            <el-tag type="info">实时数据</el-tag>
          </div>
          <div class="stat-content">
            <div class="stat-row">
              <div class="stat-item">
                <div class="stat-label">总爆仓金额</div>
                <div class="stat-value large text-primary">
                  {{ formatAmount(summaryStats.total_amount || 0) }}
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-label">总爆仓量</div>
                <div class="stat-value large text-primary">
                  {{ formatVolume(summaryStats.total_volume || 0) }}
                </div>
              </div>
            </div>
            <div class="stat-row">
              <div class="stat-item">
                <div class="stat-label">多头爆仓</div>
                <div class="stat-value text-success">
                  {{ formatAmount(summaryStats.long_amount || 0) }}
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-label">空头爆仓</div>
                <div class="stat-value text-danger">
                  {{ formatAmount(summaryStats.short_amount || 0) }}
                </div>
              </div>
            </div>
            <div class="stat-row">
              <div class="stat-item">
                <div class="stat-label">总笔数</div>
                <div class="stat-value text-info">
                  {{ formatNumber(summaryStats.total_count || 0, 0) }}
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-label">平均单笔金额</div>
                <div class="stat-value text-info">
                  {{ formatAmount(summaryStats.total_count > 0 ? summaryStats.total_amount / summaryStats.total_count : 0) }}
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 时间窗口统计 -->
        <div class="stat-card">
          <div class="stat-header">
            <h3>时间窗口分布</h3>
            <el-select v-model="selectedTimeWindow" size="small" style="width: 100px">
              <el-option
                v-for="window in timeWindows"
                :key="window.key"
                :label="window.label"
                :value="window.key"
              />
            </el-select>
          </div>
          <div class="stat-content">
            <div class="time-window-stats">
              <div class="window-stat">
                <div class="window-label">1分钟</div>
                <div class="window-value">{{ formatAmount(getTimeWindowAmount('1m')) }}</div>
              </div>
              <div class="window-stat">
                <div class="window-label">3分钟</div>
                <div class="window-value">{{ formatAmount(getTimeWindowAmount('3m')) }}</div>
              </div>
              <div class="window-stat">
                <div class="window-label">5分钟</div>
                <div class="window-value">{{ formatAmount(getTimeWindowAmount('5m')) }}</div>
              </div>
              <div class="window-stat">
                <div class="window-label">10分钟</div>
                <div class="window-value">{{ formatAmount(getTimeWindowAmount('10m')) }}</div>
              </div>
              <div class="window-stat">
                <div class="window-label">15分钟</div>
                <div class="window-value">{{ formatAmount(getTimeWindowAmount('15m')) }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 热门币种 -->
        <div class="stat-card">
          <div class="stat-header">
            <h3>热门币种 TOP10</h3>
            <el-button size="small" @click="refreshHotCoins" :loading="hotCoinsLoading">
              刷新
            </el-button>
          </div>
          <div class="stat-content">
            <div class="hot-coins-list">
<div 
                v-for="(coin, index) in hotCoins" 
                :key="coin.coin"
                class="hot-coin-item"
              >
                <div class="coin-rank">{{ index + 1 }}</div>
                <div class="coin-name">
                  <el-tag type="primary" size="small">{{ formatCoinName(coin.coin) }}</el-tag>
                </div>
                <div class="coin-amount">{{ formatAmount(coin.total_amount) }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 系统性能 -->
        <div class="stat-card">
          <div class="stat-header">
            <h3>系统性能</h3>
            <el-button size="small" @click="refreshSystemStats" :loading="systemStatsLoading">
              刷新
            </el-button>
          </div>
          <div class="stat-content">
            <div class="performance-stats">
              <div class="perf-item">
                <div class="perf-label">内存使用</div>
                <div class="perf-value">{{ formatFileSize(systemStats.memory_usage || 0) }}</div>
              </div>
              <div class="perf-item">
                <div class="perf-label">CPU使用率</div>
                <div class="perf-value">{{ formatPercent(systemStats.cpu_usage || 0) }}</div>
              </div>
              <div class="perf-item">
                <div class="perf-label">数据处理速度</div>
                <div class="perf-value">{{ formatNumber(systemStats.processing_speed || 0, 0) }}/秒</div>
              </div>
              <div class="perf-item">
                <div class="perf-label">WebSocket延迟</div>
                <div class="perf-value">{{ formatNumber(systemStats.ws_latency || 0, 0) }}ms</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 操作面板 -->
    <div class="actions-section">
      <h2>系统操作</h2>
      <div class="actions-grid">
        <el-button type="primary" size="large" @click="refreshAllData" :loading="refreshing">
          <el-icon><Refresh /></el-icon>
          刷新所有数据
        </el-button>
        
        <el-button type="success" size="large" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        
        <el-button type="warning" size="large" @click="clearCache">
          <el-icon><Delete /></el-icon>
          清理缓存
        </el-button>
        
        <el-button type="info" size="large" @click="viewLogs">
          <el-icon><Document /></el-icon>
          查看日志
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import {
  Connection,
  Close,
  DataBoard,
  Document,
  Timer,
  Refresh,
  Download,
  Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useSystemStore } from '@/stores/system'
import { useLiquidationStore } from '@/stores/liquidation'
import {
  formatAmount,
  formatVolume,
  formatNumber,
  formatPercent,
  formatFileSize,
  formatCoinName
} from '@/utils/format'

const systemStore = useSystemStore()
const liquidationStore = useLiquidationStore()

// 响应式数据
const uptime = ref(0)
const summaryStats = ref({})
const hotCoins = ref([])
const systemStats = ref({})
const selectedTimeWindow = ref('5m')
const hotCoinsLoading = ref(false)
const systemStatsLoading = ref(false)
const refreshing = ref(false)

// 时间窗口选项
const timeWindows = [
  { key: '1m', label: '1分钟' },
  { key: '3m', label: '3分钟' },
  { key: '5m', label: '5分钟' },
  { key: '10m', label: '10分钟' },
  { key: '15m', label: '15分钟' }
]

// 计算属性
const formatUptime = (seconds) => {
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (days > 0) {
    return `${days}天 ${hours}小时 ${minutes}分钟`
  } else if (hours > 0) {
    return `${hours}小时 ${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 方法
const getTimeWindowAmount = (window) => {
  return summaryStats.value[window]?.total_amount || 0
}

const refreshHotCoins = async () => {
  hotCoinsLoading.value = true
  try {
    const response = await liquidationStore.getHotCoins(10)
    hotCoins.value = response || []
  } catch (error) {
    ElMessage.error('获取热门币种失败')
  } finally {
    hotCoinsLoading.value = false
  }
}

const refreshSystemStats = async () => {
  systemStatsLoading.value = true
  try {
    const stats = await systemStore.getSystemStats()
    systemStats.value = stats || {}
  } catch (error) {
    ElMessage.error('获取系统统计失败')
  } finally {
    systemStatsLoading.value = false
  }
}

const refreshSummaryStats = async () => {
  try {
    const stats = await systemStore.getSummaryStats()
    summaryStats.value = stats || {}
  } catch (error) {
    console.error('获取汇总统计失败:', error)
  }
}

const refreshAllData = async () => {
  refreshing.value = true
  try {
    await Promise.all([
      systemStore.getSystemStats(),
      refreshSummaryStats(),
      refreshHotCoins(),
      refreshSystemStats()
    ])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    refreshing.value = false
  }
}

const exportData = async () => {
  try {
    ElMessage.info('数据导出功能开发中...')
  } catch (error) {
    ElMessage.error('数据导出失败')
  }
}

const clearCache = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清理缓存吗？这将清除所有本地存储的数据。',
      '确认清理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 清理本地存储
    localStorage.clear()
    sessionStorage.clear()
    
    ElMessage.success('缓存清理成功')
  } catch (error) {
    // 用户取消操作
  }
}

const viewLogs = () => {
  ElMessage.info('日志查看功能开发中...')
}


// 定时器
let uptimeTimer = null
let statsTimer = null

// 生命周期
onMounted(async () => {
  // 初始化数据
  await refreshAllData()
  
  // 启动运行时间计时器
  const startTime = Date.now()
  uptimeTimer = setInterval(() => {
    uptime.value = Math.floor((Date.now() - startTime) / 1000)
  }, 1000)
  
  // 启动数据刷新定时器
  statsTimer = setInterval(() => {
    refreshSummaryStats()
    systemStore.getSystemStats()
  }, 10000) // 每10秒刷新一次
})

onUnmounted(() => {
  if (uptimeTimer) {
    clearInterval(uptimeTimer)
  }
  if (statsTimer) {
    clearInterval(statsTimer)
  }
})
</script>

<style lang="scss" scoped>
.system-stats {
  .page-header {
    margin-bottom: 32px;
    
    h1 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 28px;
      font-weight: 600;
    }
    
    .page-description {
      margin: 0;
      color: #606266;
      font-size: 16px;
    }
  }
  
  .status-section,
  .stats-section,
  .actions-section {
    margin-bottom: 32px;
    
    h2 {
      margin: 0 0 20px 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }
  }
  
  .status-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
  }
  
  .status-card {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      transform: translateY(-2px);
    }
    
    .status-icon {
      flex-shrink: 0;
    }
    
    .status-content {
      flex: 1;
      
      .status-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 4px;
      }
      
      .status-value {
        font-size: 24px;
        font-weight: 600;
        margin-bottom: 4px;
      }
      
      .status-description {
        font-size: 12px;
        color: #C0C4CC;
      }
    }
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
  }
  
  .stat-card {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    &.large {
      grid-column: span 2;
    }
    
    .stat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
        color: #303133;
        font-size: 16px;
        font-weight: 600;
      }
    }
    
    .stat-content {
      .stat-row {
        display: flex;
        gap: 24px;
        margin-bottom: 16px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
      
      .stat-item {
        flex: 1;
        
        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-bottom: 4px;
        }
        
        .stat-value {
          font-size: 18px;
          font-weight: 600;
          
          &.large {
            font-size: 24px;
          }
        }
      }
    }
  }
  
  .time-window-stats {
    .window-stat {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #EBEEF5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .window-label {
        color: #606266;
        font-size: 14px;
      }
      
      .window-value {
        color: #303133;
        font-weight: 600;
      }
    }
  }
  
  .hot-coins-list {
    .hot-coin-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 8px 0;
      border-bottom: 1px solid #EBEEF5;
      cursor: pointer;
      transition: all 0.2s ease;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:hover {
        background-color: #F5F7FA;
        border-radius: 4px;
        padding-left: 8px;
        padding-right: 8px;
      }
      
      .coin-rank {
        width: 24px;
        height: 24px;
        background: #E6A23C;
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 600;
      }
      
      .coin-name {
        flex: 1;
      }
      
      .coin-amount {
        color: #303133;
        font-weight: 600;
        font-size: 14px;
      }
    }
  }
  
  .performance-stats {
    .perf-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #EBEEF5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .perf-label {
        color: #606266;
        font-size: 14px;
      }
      
      .perf-value {
        color: #303133;
        font-weight: 600;
      }
    }
  }
  
  .actions-grid {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .system-stats {
    .status-grid,
    .stats-grid {
      grid-template-columns: 1fr;
    }
    
    .stat-card.large {
      grid-column: span 1;
    }
    
    .actions-grid {
      flex-direction: column;
    }
  }
}
</style>